/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DeUpPanel.java
 *
 * Created on 01/12/2011, 01:24:50
 */
package proj5labbd.graphics.departamento;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Painel de atualização de departamento
 */
public class DeUpPanel extends OperationPanel {

    /** Creates new form DeUpPanel */
    public DeUpPanel(DeptFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbUpdate.addActionListener(new DeptAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam = new javax.swing.JPanel();
        jlbNome = new javax.swing.JLabel();
        jftxtTel = new javax.swing.JFormattedTextField();
        jlbTel = new javax.swing.JLabel();
        jtxtNome = new javax.swing.JTextField();
        jlbEm = new javax.swing.JLabel();
        jftxtEm = new javax.swing.JFormattedTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtUpdate = new javax.swing.JTable();
        jbUpdate = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Atualização"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de atualização"));

        jlbNome.setText("Nome");

        try {
            jftxtTel.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##########")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtTel.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        jlbTel.setText("Telefone");

        jlbEm.setText("Emissora (CNPJ)");

        try {
            jftxtEm.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.###.###/####-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtEm.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jftxtEm)
                    .addComponent(jlbNome, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtNome, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                    .addComponent(jlbEm))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jlbTel)
                    .addComponent(jftxtTel, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE))
                .addContainerGap(50, Short.MAX_VALUE))
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbTel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jftxtTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbNome)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbEm)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jftxtEm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jtUpdate.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtUpdate.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        jScrollPane2.setViewportView(jtUpdate);

        jbUpdate.setText("Update");
        jbUpdate.setActionCommand("Atualizar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(398, Short.MAX_VALUE)
                .addComponent(jbUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
                    .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnParam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(jbUpdate))
        );
    }// </editor-fold>//GEN-END:initComponents

    //ação tomada à apresentação do painel ao usuário
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar os dados da tabela.");
        }
    }//GEN-LAST:event_formComponentShown
    //ação tomada ao click do mouse eno painel
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtUpdate.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbUpdate;
    private javax.swing.JFormattedTextField jftxtEm;
    javax.swing.JFormattedTextField jftxtTel;
    private javax.swing.JLabel jlbEm;
    private javax.swing.JLabel jlbNome;
    private javax.swing.JLabel jlbTel;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtUpdate;
    javax.swing.JTextField jtxtNome;
    // End of variables declaration//GEN-END:variables
    //configuração da(s) tabela(s) que utiliza o resgate de informações da base de dados
    private void setupTable() throws SQLException {
        
        String [] titles = {"ID","Nome","Telefone","CNPJ da emissora",
            "Nome da emissora","Nro. de funcionários"};
        String [] fields = {"departamento.idDe","departamento.nomeDe","departamento.telefoneDe",
            "departamento.cnpjEm","emissora.nomeCompletoEm","departamento.nroFuncionariosDe"};
        String [] params = {"departamento.cnpjEm=emissora.cnpjEm"};
        String [][] s = dbInterface.view(fields, params, new String[]{"departamento","emissora"});
        
        DefaultTableModel model = new DefaultTableModel(s,titles);
        jtUpdate.setModel(model);
    }
    //ouvinte dos eventos do botão de atualização
    class DeptAction implements ActionListener {
        //ação do botão de atualização
        public void actionPerformed(ActionEvent e) {
            try {
                ArrayList<String> fields = new ArrayList<String>();
                
                if (jtxtNome.getText().trim().compareTo("") != 0) {
                    fields.add("departamento.nomeDe='"+jtxtNome.getText()+"'");
                }
                
                if (jftxtEm.getText().compareTo("  .   .   /    -  ") != 0) {
                    fields.add("departamento.cnpjEm='"+jftxtEm.getText()+"'");
                }
                
                if (jftxtTel.getText().compareTo("          ") != 0) {
                    fields.add("departamento.telefoneDe="+jftxtTel.getText());
                }
                
                if (fields.size() > 0 && jtUpdate.getSelectedRowCount() > 0) {
                    String s;
                    String [] params = new String[1];
                    String [] fieldsArray = new String[fields.size()];
                    fields.toArray(fieldsArray);
                    int [] rows = jtUpdate.getSelectedRows();
                    for ( int i = 0; i < rows.length; i++ ) {
                        try {
                            s = "departamento.idDe="+jtUpdate.getValueAt(rows[i],0).toString();
                            params[0] = s;
                            dbInterface.update(fieldsArray, params,
                                    new String[]{"departamento"});
                        } catch (SQLException ex) {
                            frame.printException(ex);
                            JOptionPane.showMessageDialog(null, "Não foi possível "
                                    + "atualizar os dados da " + rows[i] + "linha no banco.");
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Você deve selecionar os "
                            + "registros a serem modificados e inserir nos campos as modificações");
                }
                
                jtUpdate.clearSelection();
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }
        }
    }
    
}
